package cn.com.open.ms.ecgpaasdatarest.dynamicsql;

import cn.com.open.ms.ecgpaasdatarest.enums.SQLEnums;
import lombok.extern.java.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Description 动态SQL拼接
 * @author 奶茶
 * Created by on 2018/11/29 9:38.
 */
public class DynamicSqlUtils {

    private static final Logger log = LoggerFactory.getLogger(DynamicSqlUtils.class);

    public static String getSQL(String tableName) {
        //获取当前线程的request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        Enumeration<String> parameterNames = request.getParameterNames();

        StringBuilder selectColumnBuilder = new StringBuilder(SQLEnums.SELECT.getSqlName()).append(" ");
        StringBuilder selectConditionBuilder = new StringBuilder(SQLEnums.WHERE.getSqlName()).append(" 1=1 ");
        Boolean isColumns = true;
        while (parameterNames.hasMoreElements()){
            String parameterName = parameterNames.nextElement();
            String parameterValue = request.getParameter(parameterName);
            if(parameterName.equals(SQLEnums.SELECT.getSqlAlias())){
                selectColumnBuilder.append(parameterValue);
                isColumns = false;
            }else{
                selectConditionBuilder = DynamicSqlFactory.joinSQL(parameterName,parameterValue,selectConditionBuilder);
            }
        }

        //判断是否存在查询列
        if(isColumns){
            selectColumnBuilder.append(SQLEnums.COLUMN.getSqlName());
        }

        String sql = selectColumnBuilder
                .append(" ")
                .append(SQLEnums.FROM.getSqlName())
                .append(" ")
                .append(tableName)
                .append(" ")
                .append(selectConditionBuilder)
                .toString();
        log.info(sql);
        return sql;
    }

}
